package com.learning.security;

import com.learning.security.dal.dataobject.UserDO;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SecurityLabApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecurityLabApplication.class, args);
    }

    @PostMapping("/login")
    public String login(String username, String password) {
        return "login";
    }

    @GetMapping("/test")
    public String test() {
        System.out.println("Hello Spring Security!");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();// 获得认证信息
        System.out.println("authentication.getName() = " + authentication.getName());
        System.out.println("authentication.getAuthorities() = " + authentication.getAuthorities());
        System.out.println("authentication.getCredentials() = " + authentication.getCredentials());
        System.out.println("authentication.getDetails() = " + authentication.getDetails());
        System.out.println("authentication.getPrincipal() = " + authentication.getPrincipal());
        UserDO principal = (UserDO) authentication.getPrincipal();// 返回值类型为User时需要进行强制转换 org.springframework.security.core.userdetails.User
        System.out.println("principal.getUsername() = " + principal.getUsername());
        System.out.println("principal.getPassword() = " + principal.getPassword());
        System.out.println("principal.getAuthorities() = " + principal.getAuthorities());
        return "test";
    }

    @GetMapping("multiThreadAsyncUserInfo")
    public String multiThreadAsyncUserInfo() throws InterruptedException {
        System.out.println("Hello Spring Security!");
        new Thread(() -> {
            Authentication Authentication = SecurityContextHolder.getContext().getAuthentication();
            User childPrincipal = (User) Authentication.getPrincipal();
            System.out.println("Principal.getUsername() = " + childPrincipal.getUsername());
            System.out.println("Principal.getPassword() = " + childPrincipal.getPassword());
            System.out.println("Principal.getAuthorities() = " + childPrincipal.getAuthorities());
        }).start();
        return "multiThreadAsyncUserInfo";
    }
}
